package org.deltaset.faces;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * would be removed
 * @author dmakariev
 */
@Deprecated
public class GetLongIdConverter<T> implements Converter {

    public GetLongIdConverter(Class<T> clazz) {
        this.clazz = clazz;
    }
    private final Class<T> clazz;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (null == value) {
            return null;
        }
        final Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
        final String key = clazz.getName() + "_" + value;
        return viewMap.get(key);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (null == value) {
            throw new IllegalArgumentException("ownerConverter cannot convert NULL object");
        }
        try {
            @SuppressWarnings("unchecked")
            T t = (T) value;
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(this.getClass().getName() + " supports only :" + clazz.getName() + "  cannot convert " + value.getClass().getName());
        }

        final Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
        final String id = findIdValue(value);
        final String key = clazz.getName() + "_" + id;
        viewMap.put(key, value);
        return id;
    }

    private <T> String findIdValue(Object object) {
        try {
            Method m = clazz.getDeclaredMethod("getId");
            Long id = (Long) m.invoke(object);
            return id.toString();
        } catch (IllegalAccessException ex) {
        } catch (IllegalArgumentException ex) {
        } catch (InvocationTargetException ex) {
        } catch (NoSuchMethodException ex) {
        } catch (SecurityException ex) {
        }
        throw new IllegalArgumentException("doens't support 'Long getId()' method; class=" + object.getClass().getName());
    }
}
